package io.jee.medusa.orm.utils;

import io.jee.medusa.orm.condition.Condition;
import io.jee.medusa.orm.condition.ConditionGroup;
import io.jee.medusa.orm.condition.ConditionValue;

import java.util.List;
import java.util.Map;

public class SQLUtils {

	/**
	 * 根据params生成where字句
	 *
	 * @category author: ynshun
	 * @since: 2014年11月10日
	 * @created: 下午4:53:16
	 * @param params
	 * @return
	 */
	public static String analyse(Map<String, Object> params) {
		if (params == null)
			return "";

		StringBuffer sql = new StringBuffer(" where 1 = 1");
		for (String key : params.keySet()) {
			sql.append(" and t0.").append(key).append(" = :").append(key.replaceAll("\\.", ""));
		}
		return sql.toString();
	}

	/**
	 * 根据params生成where字句
	 *
	 * @category 
	 * @author: ynshun
	 * @since: 2014年11月10日
	 * @created: 下午4:53:48
	 * @param group
	 * @return
	 */
	public static String analyse(ConditionGroup group) {
		if (group == null)
			return "";
		StringBuffer sql = new StringBuffer();
		List<Condition> conditions = group.getConditions();
		List<ConditionGroup> groups = group.getGroups();

		String relation;
		String opType;
		ConditionValue conditionValue;
		Boolean isFirst = true;
		for (Condition condition : conditions) {
			isFirst = false;
			conditionValue = condition.getConditionValue();
			opType = Condition.getStaticResource(conditionValue.getOpType());
			relation = condition.isFirst() ? "" : Condition.getStaticResource(condition.getRelation());
			if (conditionValue.getOpType().equals(15)) { // is null
				sql.append(relation).append(" t0." + conditionValue.getKey()).append(opType);
				continue;
			} else if (conditionValue.getOpType().equals(16)) { // is not null
				sql.append(relation).append(" t0." + conditionValue.getKey()).append(opType);
				continue;
			}
			sql.append(relation).append(" t0." + conditionValue.getKey()).append(opType).append(":").append(conditionValue.getKey().replaceAll("\\.", ""));
		}

		for (ConditionGroup tempGroup : groups) {
			relation = Condition.getStaticResource(tempGroup.getRelation());
			sql.append(isFirst ? "" : relation).append("(").append(analyse(tempGroup)).append(")");
			isFirst = false;
		}
		return sql.toString();
	}

	/**
	 * 根据条件和配置生成完整where字句
	 *
	 * @category 
	 * @author: ynshun
	 * @since: 2014年11月10日
	 * @created: 下午4:55:32
	 * @param group
	 * @param isFull
	 * @return
	 */
	public static String analyse(ConditionGroup group, boolean isFull) {
		if (group == null)
			return "";
		String sql = analyse(group);
		if (isFull && sql.length() > 0) {
			sql = " where " + sql;
		}
		return sql;
	}
	
	/**
	 * 根据对象实例生成Insert-SQL语句
	 *
	 * @category 
	 * @author: ynshun
	 * @since: 2014年11月10日
	 * @created: 下午5:30:06
	 * @param entity
	 * @return
	 */
	@SuppressWarnings("unused")
	public static <T> String genInsertSQL(T entity) {
		StringBuffer sql = new StringBuffer("");
		try {
			Class<?> clz = entity.getClass();
			
		} catch (Exception e) {
			
		}
		return "";
	}
	
}
